<template>
	<view class="travel_bus_list">
		<view class="top-wrap">
			<view class="date-wrap">
				<view class="calendar-wrap">
					<image class="calendar-icon" src="@/static/imgs/icons/calendar-icon.png" mode=""></image>
					<text @click="handleChooseDate('go',choosedDateObj.go_full)">{{startDate}}</text>
					<text style="padding: 0 10rpx;">—</text>
					<text @click="handleChooseDate('back',choosedDateObj.back_full)">{{endDate}}</text>
				</view>
			</view>

			<view class="travel_model-list">
				<view class="travel_model-item" :class="{active: curTravelModel.alias === it_model.alias}" v-for="(it_model, in_model) in travelModelList"
				 :key="in_model" @click="handleChooseTravelModel(it_model, in_model)">{{it_model.name}}</view>
			</view>

			<view class="nav_ul">
				<view class="nav_li" :class="{active: curNav==='all'}" @click="selecTime">出发时间</view>
				<view class="nav_li" :class="{active: curNav!=='all'}">
					<view class="li_price" @click="handleSwitchNav('price')">
						<view>价格</view>
						<view v-if="priceStatus==='up'" class="icon">
							<image src="@/static/imgs/icons/price-down-icon.png" mode=""></image>
						</view>
						<view v-else class="icon">
							<image src="@/static/imgs/icons/price-up-icon.png" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="swiper-wrap" :style="{height: DOMTopWrapHeight + 'rpx'}">
			<swiper class="swiper" :current="curSwiperIndex" @change="handleSwiper">
				<swiper-item>
					<scroll-view scroll-y="true" class="content-wrap" :scroll-top="scrollTop" :scroll-with-animation="true" @scroll="onScrollTopNew" :style="{height: DOMTopWrapHeight - 20 + 'rpx'}"
					 refresher-enabled enable-back-to-top @scrolltolower="handleScrolltolower" :refresher-triggered="refresherTriggered"
					 @refresherrefresh="handleRefresherrefresh">
						<view class="bus_list" v-if="list.length">
							<view class="bus_item" v-for="(item,index) in list" :key="index" @click="handleChooseShift(item, 'single')">
								<view class="l-wrap">
									<text class="time">{{item.startTime}}</text>
									<view class="bus-icon">
										<image src="@/static/imgs/icons/bus-icon.png" mode=""></image>
									</view>
									<text class="bus_type">{{item.shiftsCartype}}</text>
								</view>
								<view class="r-wrap">
									<view class="address-wrap">
										<view class="step-wrap">
											<view class="dot dot_from"></view>
											<view class="dot dot_to"></view>
										</view>
										<text class="from ellispsis1">{{item.startStation}}</text>
										<text class="to ellispsis1">{{item.arriveStation}}</text>
										<view class="time-wrap">
											<view class="time-icon">
												<image src="@/static/imgs/icons/time-icon.png" mode=""></image>
											</view>
											<text class="time">预计到达时间：{{item.arriveTime}}</text>
										</view>
									</view>
									<view class="ticket-wrap">
										<view class="ticket">
											<view class="price">￥{{item.linePrice}}</view>
											<!-- <view class="num">余{{item.lastNumber}}张</view> -->
											<view v-if="item.status ==  0" class="num">余{{item.lastNumber}}张</view>
											<view v-if="item.status ==  1" class="num">暂停售票</view>
											<view v-if="item.status ==  2" class="num">无票</view>
										</view>
									</view>
								</view>
								<view class="" v-if="item.status ==  0">
									<uni-icons v-if="item.choosed" class="choose-icon" color="#FFAF3C" type="circle-filled" size="22"></uni-icons>
									<uni-icons v-else class="choose-icon" color="#999" type="circle" size="22"></uni-icons>
								</view>

							</view>
						</view>
						<view class="noData" v-else>当前所选出发时间暂无班次信息啦~~~</view>
					</scroll-view>
				</swiper-item>
				<swiper-item>
					<scroll-view scroll-y="true" class="content-wrap" :style="{height: DOMTopWrapHeight - 20 + 'rpx'}" :scroll-top="scrollTop" :scroll-with-animation="true" @scroll="onScrollTopNew"
					 refresher-enabled enable-back-to-top @scrolltolower="handleScrolltolower" :refresher-triggered="refresherTriggered"
					 @refresherrefresh="handleRefresherrefresh">
						<view class="bus_list" v-if="toAndForList.length">
							<view class="bus_item" v-for="(item,index) in toAndForList" :key="index" @click="handleChooseShift(item, 'double')">
								<view class="l-wrap">
									<text class="time">{{item.startTime}}</text>
									<view class="bus-icon">
										<image src="@/static/imgs/icons/bus-icon.png" mode=""></image>
									</view>
									<text class="bus_type">{{item.shiftsCartype}}</text>
								</view>
								<view class="r-wrap">
									<view class="address-wrap">
										<view class="step-wrap">
											<view class="dot dot_from"></view>
											<view class="dot dot_to"></view>
										</view>
										<text class="from ellispsis1">{{item.startStation}}</text>
										<text class="to ellispsis1">{{item.arriveStation}}</text>
										<view class="time-wrap">
											<view class="time-icon">
												<image src="@/static/imgs/icons/time-icon.png" mode=""></image>
											</view>
											<text class="time">预计到达时间：{{item.arriveTime}}</text>
										</view>
									</view>
									<view class="ticket-wrap">
										<view class="ticket">
											<view class="price">￥{{item.linePrice}}</view>
											<!-- <view class="num">余{{item.lastNumber}}张</view> -->
											<view v-if="item.status ==  0" class="num">余{{item.lastNumber}}张</view>
											<view v-if="item.status ==  1" class="num">暂停售票</view>
											<view v-if="item.status ==  2" class="num">无票</view>
										</view>
									</view>
								</view>
								<view class="" v-if="item.status ==  0">
									<uni-icons v-if="item.choosed" class="choose-icon" color="#FFAF3C" type="circle-filled" size="22"></uni-icons>
									<uni-icons v-else class="choose-icon" color="#999" type="circle" size="22"></uni-icons>
								</view>

							</view>
						</view>
						<view class="noData" v-else>当前所选返程时间暂无班次信息啦~~~</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>

		<view class="fab_btn-wrap" @click="goToFWb(4,'出行攻略')">
			<image src="../static/imgs/icons/fab-icon.png" mode="aspectFill"></image>
		</view>

		<commonAlert :config="alertConfig" ref="alert" @confirm="handleConfirm"></commonAlert>
	</view>
</template>

<script>
	import calendar from '@/components/tp-calendar/util.js'
	import commonAlert from '@/components/common/common-alert.vue'
	import $DB from '@/utils/debounce.js'
	export default {
		components: {
			commonAlert
		},
		data() {
			return {
				alertConfig: {
					cancleText: '我再想想',
					confirmText: '我确定了',
					content: '是否确定所选班次？'
				},
				curTravelModel: {
					name: '出发',
					alias: 'from'
				},
				curSwiperIndex: 0,
				travelModelList: [{
					name: '出发',
					alias: 'from'
				}, {
					name: '返程',
					alias: 'to'
				}],
				choosedDateObj: {}, // 选择出行时间
				choosedAddressObj: {}, // 选择出行时间
				startDate: '', // 05月21日 周四
				endDate: '', // 05月21日 周四
				list: [],
				toAndForList: [], // 往返可选班次列表
				curNav: 'price',
				priceStatus: 'up',
				curChoosedShift: {}, // 当前所选班次
				page: {
					pageNum: 1,
					last_page: 0,
					pageSize: 10,
				},
				DOMTopWrapHeight: 0, // 顶部wrap 高度
				delayDay: 0, // // 默认可以选择几天后的日期
				type: 0, // 出发时段 	0不限   1.0-6  2.6-12  3.12-18 4.18-24 . 搜索的时间段. 默认是0
				// #ifdef H5
				durationDay: 100800, //小时 可以选择多少天内的 60天
				// #endif

				refresherTriggered: true, // 设置当前下拉刷新状态
				scrollTop: 0, // 设置竖向滚动条位置
			};
		},
		onLoad(opt) {
			this.delayDay = opt && opt.delayDay
			this.initDate()
		},
		onShow() {
			this.page.pageNum = 1
			this.getChoosedAddress()
			this.updateChoosedDate()
			this.getDOMTopWrapHeight()
		},
		computed: {
			startDateFull() {
				return this.choosedDateObj.go_full
			},
			endDateFull() {
				return this.choosedDateObj.back_full
			},
		},
		methods: {
			// 选择出发时间
			selecTime() {
				const _this = this
				uni.showActionSheet({
					itemList: ['不限', '00:00-06:00', '06:00-12:00', '12:00-18:00', '18:00-24:00'],
					success: function(res) {
						// console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
						_this.type = res.tapIndex
						_this.page.pageNum = 1
						// _this.getBusList()
						if (_this.curTravelModel.name == '出发') {
							_this.getBusListGo()
						} else {
							if (_this.curChoosedShift.from.shiftsId) {
								_this.getBusListBack()
							} else {
								uni.showToast({
									title: '请选择出发路线',
									icon: 'none'
								})
							}
						}

					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			handleSwiper(e) {
				let i = e.detail.current
				if (i === 1 && this.curChoosedShift.from) {
					this.getBusListBack()
				} else {
					this.curChoosedShift.to = ''
				}
				this.curTravelModel = this.travelModelList[i]
				this.curSwiperIndex = i

			},
			handleChooseDate(sts, date) {
				uni.navigateTo({
					// #ifdef MP-WEIXIN
					url: '../pages/others/calendar?sts=' + sts + '&delayDay=' + this.delayDay + '&choosedDay=' + date
					// #endif
					// #ifdef H5
					url: '../pages/others/calendar?sts=' + sts + '&delayDay=' + this.delayDay + '&choosedDay=' + date +
						'&durationDay=' + this.durationDay
					// #endif
				})
			},
			handleSwitchNav(it) {
				if (it === 'price' && this.priceStatus === 'up' && this.curNav === 'price') {
					this.priceStatus = 'down'
				} else if (it === 'price' && this.priceStatus === 'down' && this.curNav === 'price') {
					this.priceStatus = 'up'
				}
				this.curNav = it
				this.page.pageNum = 1
				if (this.curTravelModel.name == '出发') {
					this.getBusListGo()
				} else {
					this.getBusListBack()
				}
			},
			handleChooseShift(item, type) {
				if (item.status == 1) {
					return uni.showToast({
						title: '暂停售票',
						icon: 'none'
					})
				}
				if (item.status == 2) {
					return uni.showToast({
						title: '已售罄',
						icon: 'none'
					})
				}
				this.type = 0
				this.page.pageNum = 1
				if (type === 'single') {
					this.list.map(ite => {
						ite.choosed = false
					})
					item.choosed = true
					this.curChoosedShift.from = item
					if (!this.curChoosedShift.to && this.curChoosedShift.from) {
						this.curSwiperIndex = 1
					}
				} else {
					this.toAndForList.map(ite => {
						ite.choosed = false
					})
					item.choosed = true
					this.curChoosedShift.to = item
					if (!this.curChoosedShift.from) {
						this.curSwiperIndex = 0
					}
				}


				let {
					alias
				} = this.curTravelModel
				this.$set(this.curChoosedShift, alias, item)
				let {
					from,
					to
				} = this.curChoosedShift
				if (from && to) {
					this.$refs.alert.show()
				}
			},
			handleChooseTravelModel(item, i) {
				this.page.pageNum = 1
				if (i == 1) { // 出发
					let arr = this.list.filter(item => item.choosed)
					if (arr.length) {
						this.curTravelModel = item;
						this.curSwiperIndex = i
						this.getBusListBack()
					}
				} else {
					this.curTravelModel = item;
					this.curSwiperIndex = i
					this.getBusListGo()
				}
			},
			handleConfirm() {
				let busInfo = JSON.stringify(this.curChoosedShift)
				uni.navigateTo({
					url: '../pages/order/bus.order.toAndFor?busInfo=' + busInfo
				});
			},
			updateChoosedDate() {
				this.choosedDateObj = this.$store.getters.getHomeChoosedDateObj;
				let obj = this.choosedDateObj;
				if (this.choosedDateObj.go) {
					this.$set(this.choosedDateObj, 'go', obj.go);
					this.startDate = this.formatDate(obj.go_full)
				}
				if (this.choosedDateObj.back) {
					this.$set(this.choosedDateObj, 'back', obj.back);
					this.endDate = this.formatDate(obj.back_full)
				}
			},
			// 初始化时间
			initDate() {
				this.choosedDateObj = this.$store.getters.getHomeChoosedDateObj
				let {
					year: startYear,
					month: startMonth,
					day: startDay
				} = this.choosedDateObj.go_obj || calendar.getDateObj()
				let startDate = startYear + '-' + startMonth + '-' + startDay
				this.startDate = this.formatDate(startDate)

				let {
					year: endYear,
					month: endMonth,
					day: endDay
				} = this.choosedDateObj.back_obj || calendar.getDateObj()
				let endDate = endYear + '-' + endMonth + '-' + endDay
				this.endDate = this.formatDate(endDate)
			},
			formatDate(date) {
				let dateObj = calendar.getDateObj(date)
				let {
					year,
					month,
					day,
					week
				} = dateObj
				switch (week) {
					case 0:
						week = '周日'
						break
					case 1:
						week = '周一'
						break
					case 2:
						week = '周二'
						break
					case 3:
						week = '周三'
						break
					case 4:
						week = '周四'
						break
					case 5:
						week = '周五'
						break
					case 6:
						week = '周六'
						break
				}
				return month + '月' + day + '日' + ' ' + week
			},
			getChoosedAddress() {
				this.choosedAddressObj = this.$store.getters.getHomeChoosedAddressObj
				// this.getBusListGo()
				if (this.curTravelModel.name == '出发') {
					this.getBusListGo()
				} else {
					this.getBusListBack()
				}
			},
			// 去的列表
			getBusListGo() {
				// this.page.pageNum = 1
				const beginStation = this.choosedAddressObj.from && this.choosedAddressObj.from.id
				const endStation = this.choosedAddressObj.to && this.choosedAddressObj.to.id
				const goTime = this.choosedDateObj.go_full
				const backTime = this.choosedDateObj.back_full
				const orderBy = this.priceStatus === 'up' ? 'asc' : 'desc'
				const pageSize = this.page.pageSize
				const pageNum = this.page.pageNum
				const type = this.type
				const regularType = uni.getStorageSync('trlineid')
				this.$http.get(this.$api.getBusList, {
					beginStation,
					endStation,
					goTime,
					regularType,
					backTime,
					orderBy,
					pageSize,
					pageNum,
					type
				}).then(res => {
					this.stopPullDownRefresh()
					if (res.code === 200) {
						this.page.last_page = res.data.pageTotal
						if (res.data.result) {
							res.data.result.map(item => {
								item.choosed = false
							})
						}
						if (this.page.pageNum > 1) {
							this.list = this.list.concat(JSON.parse(JSON.stringify(res.data.result)))
						} else {
							this.list = JSON.parse(JSON.stringify(res.data.result))
							this.scrollTop = 0
							// console.log('getBusListGo');
							// uni.pageScrollTo({
							//     scrollTop: 0,
							//     duration: 300
							// });
						}
						this.curChoosedShift = {}
					}
					console.log(this.list);
				})
			},
			// 返程的列表
			getBusListBack() {
				// this.page.pageNum = 1
				const beginStation = this.choosedAddressObj.to && this.choosedAddressObj.to.id
				const endStation = this.choosedAddressObj.from && this.choosedAddressObj.from.id
				const goTime = this.choosedDateObj.go_full
				const backTime = this.choosedDateObj.back_full
				const orderBy = this.priceStatus === 'up' ? 'asc' : 'desc'
				const pageSize = this.page.pageSize
				const pageNum = this.page.pageNum
				const type = this.type
				const regularType = uni.getStorageSync('trlineid')
				this.$http.get(this.$api.getBusList, {
					beginStation,
					endStation,
					goTime,
					regularType,
					backTime,
					orderBy,
					pageSize,
					pageNum,
					type,
					shiftsId: this.curChoosedShift.from.shiftsId
				}).then(res => {
					this.stopPullDownRefresh()
					if (res.code === 200) {
						this.page.last_page = res.data.pageTotal
						if (res.data.result) {
							res.data.result.map(item => {
								item.choosed = false
							})
						}
						if (this.page.pageNum > 1) {
							this.toAndForList = this.toAndForList.concat(JSON.parse(JSON.stringify(res.data.result)))
						} else {
							this.toAndForList = JSON.parse(JSON.stringify(res.data.result))
							this.scrollTop = 0
							// console.log('getBusListBack');
							// uni.pageScrollTo({
							//     scrollTop: 0,
							//     duration: 300
							// });
						}
					}
				})
			},
			// 滚动到底部
			handleScrolltolower(item, i) {
				// console.log('handleScrolltolower滚动到底部', item, i);
				this.showLoadMore = true;
				if (this.page.pageNum < this.page.last_page) {
					this.page.pageNum++
					if (this.curTravelModel.name == '出发') {
						this.getBusListGo()
					} else {
						this.getBusListBack()
					}
				} else {
					this.loadMoreText = "已没有更多数据!"
				}
			},
			// // 下拉刷新
			handleRefresherrefresh() {
				this.refresherTriggered = true
				this.page.pageNum = 1
				if (this.curTravelModel.name == '出发') {
					this.getBusListGo()
				} else {
					this.getBusListBack()
				}
			},
			// 停止刷新
			stopPullDownRefresh() {
				this.refresherTriggered = false
			},
			getDOMTopWrapHeight() {
				let _this = this
				const res = uni.getSystemInfoSync();
				const windowHeight = res.windowHeight // 可使用窗口宽度
				console.log('windowHeight', windowHeight);
				uni.getSystemInfo({
					success(res) { // res - 各种参数
						let info = uni.createSelectorQuery().select(".top-wrap");
						info.boundingClientRect(function(data) { //data - 各种参数
							console.log(data);
							_this.DOMTopWrapHeight = (windowHeight - (data && data.height)) * 2
						}).exec()
					}
				});
			},
			//去富文本页面
			goToFWb(type, name) {
				uni.navigateTo({
					url: '/pages/others/depositRule?type=' + type + '&name=' + name
				})
			},
			onScrollTopNew: $DB(function(e){
				this.scrollTop = e.detail.scrollTop
				// console.log('scrollTopNew',this.scrollTopNew);
			})
		}
	}
</script>

<style lang="scss" scoped>
	.top-wrap {
		background-color: #fff;
		font-size: 30rpx;
		position: sticky;
		position: -webkit-sticky;
		z-index: 9;
		top: 0;

		.date-wrap {
			height: 88rpx;
			padding: 0 110rpx;
			display: flex;
			align-items: center;
			justify-content: space-evenly;

			.calendar-wrap {
				height: 64rpx;
				display: flex;
				align-items: center;
				text-align: center;
				justify-content: space-evenly;
				border-radius: 12rpx;

				.calendar-icon {
					height: 28rpx;
					width: 28rpx;
					margin-right: 12rpx;
				}
			}

			.btn {
				font-size: 28rpx;
				color: #666;
			}
		}

		.travel_model-list {
			font-size: 32rpx;
			font-weight: bold;
			display: flex;
			justify-content: space-evenly;
			padding: 16rpx 0;
			border-bottom: 1px solid #EBEBEB;

			.travel_model-item {
				&.active {
					color: $blue;
				}
			}
		}

		.nav_ul {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			border-bottom: 1px solid #f5f5f5;

			.nav_li {
				display: flex;
				flex: 1;
				justify-content: space-evenly;
				align-items: center;

				&.active {
					color: $blue;
				}

				.icon {
					width: 24rpx;
					height: 30rpx;
					margin-left: 10rpx;
				}

				.li_price {
					display: flex;
					align-items: center;
				}
			}
		}
	}

	.bus_list {
		.bus_item {
			padding: 40rpx 30rpx;
			display: flex;
			background-color: #fff;
			margin: 20rpx 0 0;
			position: relative;

			.l-wrap {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: space-between;
				margin-right: 50rpx;

				.time {
					font-size: 36rpx;
					font-weight: bold;
				}

				.bus-icon {
					height: 40rpx;
					width: 40rpx;
					padding: 20rpx 0;
				}

				.bus_type {
					font-size: 24rpx;
					color: #999;
				}
			}

			.r-wrap {
				display: flex;
				flex: 1;
				justify-content: space-between;

				.address-wrap {
					display: flex;
					flex: 1;
					flex-direction: column;
					justify-content: space-between;
					font-size: 30rpx;
					font-weight: bold;
					position: relative;

					.step-wrap {
						display: flex;
						justify-content: space-between;
						flex-direction: column;
						height: 90rpx;
						position: absolute;
						top: 10rpx;
						left: 0rpx;

						&::before {
							content: '';
							position: absolute;
							left: 50%;
							transform: translateX(-50%);
							height: 100%;
							width: 1px;
							background-color: #ccc;
						}

						.dot {
							height: 20rpx;
							width: 20rpx;
							border: 1px solid #ccc;
							border-radius: 50%;
							position: relative;

							&::before {
								content: '';
								position: absolute;
								left: 50%;
								top: 50%;
								transform: translate(-50%, -50%);
								height: 100%;
								width: 100%;
								border-radius: 50%;
								background-color: #fff;
							}
						}
					}

					.from,
					.to {
						padding-left: 44rpx;
					}

					.time-wrap {
						font-size: 24rpx;
						color: #999;
						font-weight: normal;
						display: flex;
						align-items: center;

						.time-icon {
							height: 24rpx;
							width: 24rpx;
							margin-right: 15rpx;
						}
					}
				}

				.ticket-wrap {
					display: flex;
					flex-direction: column;
					justify-content: space-evenly;
					font-size: 24rpx;
					text-align: right;
					// width: 100rpx;

					.price {
						font-weight: bold;
						color: #FF4A37;
						font-size: 34rpx;
					}

					.num {
						font-weight: normal;
						color: #999;
						margin-top: 19rpx;
					}
				}
			}

			.choose-icon {
				position: absolute;
				right: 16rpx;
				top: 16rpx;
			}
		}
	}

	.noData {
		text-align: center;
		margin: 100rpx auto;
		color: #999;
	}

	.fab_btn-wrap {
		height: 88rpx;
		width: 88rpx;
		position: fixed;
		right: 30rpx;
		bottom: 200rpx;
		z-index: 9;
	}

	.swiper-wrap {
		.swiper {
			.swiper-item {
				.content-wrap {
					height: 100%;
					box-sizing: border-box;

					.content {
						padding: 20rpx 30rpx;
					}
				}
			}
		}
	}
</style>
